﻿using Microsoft.EntityFrameworkCore.Metadata.Internal;
using S.Common.EditReproductivePresenceStateHelper;
using S.PurchaseAndSales.Domain.Enum;
using S.PurchaseAndSales.Domain.Model;
using S.PurchaseAndSales.Domain.SqlServer;
using S.PurchaseAndSales.Infrastructure.Interface.PurchaseForm;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using S.PurchaseAndSales.Domain.Dto;
using S.Common.helper;
using static S.Common.EditReproductivePresenceStateHelper.EditReproductivePresenceState;
using Newtonsoft.Json;
using Microsoft.Data.SqlClient;
using Dapper;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace S.PurchaseAndSales.Infrastructure.Impl.PurchaseForm
{
    /// <summary>
    /// 羊只采购
    /// </summary>
    public class PurchaseFormRepository : BaseRepository<PurchaseFormModel>, IPurchaseFormRepository
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IConfiguration configuration;

        public PurchaseFormRepository(SqlDbContext db, IConfiguration configuration, IHttpContextAccessor httpContextAccessor) : base(db)
        {
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 显示采购信息
        /// </summary>
        /// <param name="createBy">采购人</param>
        /// <param name="createDate">采购时间</param>
        /// <param name="summaryEnum">摘要</param>
        /// <param name="warehouse">仓库</param>
        /// <param name="buildingId">栋舍</param>
        /// <returns></returns>
        public async Task<IQueryable<GetPurchaseFormDto>> GetPurchaseFormModel() 
        {
            //List<PurchaseFormModel> list = db.PurchaseFormModels.Where(x => (string.IsNullOrEmpty(createBy) || x.Buyer==createBy) && (string.IsNullOrEmpty(createDate) || x.DateOfPurchase >= DateTime.Parse(createDate))&& (string.IsNullOrEmpty(createDate)|| x.DateOfPurchase < DateTime.Parse(createDate).AddDays(1) )&& (summaryEnum == 0 || x.SummaryEnum == (SummaryEnum)summaryEnum) && (string.IsNullOrEmpty(warehouse) || x.Warehouse.Contains( warehouse)) && x.IsDel==false &&  (buildingId==0 || x.BuildingId==buildingId)).ToList();

            string connectionString = configuration.GetValue<string>("ConnectionStrings");

            using (var connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();

                    StringBuilder sqlQuery = new StringBuilder();
                    sqlQuery.Append(@"
                        SELECT a.PurchaseFormId, a.Warehouse, a.Document, a.BatchEarHorns, a.BuildingId,
                           b.BuildingName, a.ColumnId, c.ColumnName, a.Gender, a.GoodName, a.LabelPackage,
                           a.UnitOfMeasure, a.InboundQuantity, a.AverageUnitOnly, a.Amount, a.UnitDiscounts,
                           a.AdjustTheAmount, a.SettlementAmount, a.TotalWeight, a.PurchaseFormDesc,
                           a.SummaryEnum, a.CreateBy, a.CreateTime, a.UpdateBy, a.UpdateTime, a.IsAudit,a.IsWarehouse
                        FROM dbo.PurchaseFormModels AS a
                        JOIN dbo.ColumnManagementModel AS b ON a.BuildingId = b.BuildingManagementId
                        JOIN dbo.FieldModel AS c ON a.ColumnId = c.ColumnManagementId
                        WHERE a.IsDel = 0
                        ORDER BY a.CreateTime DESC;");

                    var result = connection.Query<GetPurchaseFormDto>(sqlQuery.ToString()).AsQueryable();

                    return await Task.FromResult(result);
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 批量添加采购表
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        public async Task<bool> AddRangePurchaseForm(List<PurchaseFormModel> models)
        {
          //添加采购信息
           db.PurchaseFormModels.AddRange(models);
           return await db.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 批量逻辑删除
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="updateBy"></param>
        /// <returns></returns>
        public async Task<bool> DeletePurchaseFormByIds(int[] ids, string updateBy)
        {
            List<PurchaseFormModel> list = db.PurchaseFormModels.Where(x => ids.Contains(x.PurchaseFormId)).ToList();
            foreach (var item in list)
            {
                item.IsDel = true;
                item.UpdateBy = updateBy;
                item.UpdateTime = DateTime.Now;
            }

            db.UpdateRange(list);
            return await db.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 财务审核
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="updateBy"></param>
        /// <returns></returns>
        public async Task<bool> AuditPurchaseFormByIds(int[] ids, string updateBy)
        {
            List<PurchaseFormModel> list=db.PurchaseFormModels.Where(x=>ids.Contains(x.PurchaseFormId)).ToList();
            foreach (var item in list)
            {
                item.IsAudit=true;
                item.UpdateBy = updateBy;
                item.UpdateTime= DateTime.Now;  
            }

            db.UpdateRange(list);
            return await db.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 仓库审核
        /// </summary>
        /// <returns></returns>
        public async Task<bool> RoundUpPurchaseForm(int[] ids, string updateBy)
        {
            List<PurchaseFormModel> list = db.PurchaseFormModels.Where(x => ids.Contains(x.PurchaseFormId)).ToList();
            foreach (var item in list)
            {
                item.IsWarehouse = true;
                item.UpdateBy = updateBy;
                item.UpdateTime = DateTime.Now;
            }

            db.UpdateRange(list);
           

            string konggaIP = configuration.GetValue<string>("GetKongaIp");
            string authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer "))
            {
                authHeader = authHeader.Substring("Bearer ".Length).Trim();
            }
            try
            {
                #region 修改羊只档案的状态为在场
                List<string> earTag = new List<string>();
                Transfer sheep = new Transfer();
                foreach (PurchaseFormModel model in list)
                {
                    earTag.Add(model.BatchEarHorns);
                    #region 给羊只分配栋舍
                    AddRangeSheepRescissionDto dto = new AddRangeSheepRescissionDto()
                    {
                        EarTag = model.BatchEarHorns,//可视耳标
                        SurrenderDate = DateTime.Now,//转舍日期
                        RoundType = 8,//转舍类型
                        ShiftToBuild = model.BuildingId,//转入栋舍
                        ShiftToHuts = model.ColumnId,//转入栏位
                        ShiftToBuildingManagementId = model.BuildingId,//转入栋舍主键
                        ShiftToColumnManagementId = model.ColumnId,//转入栏位主键
                        CreateBy = model.CreateBy,//创建人
                        CreateDate = model.CreateTime,///创建时间
                        Sex = (int)model.Gender,//性别
                        TransFerType=8//转舍事件
                    };
                    sheep.sheep.Add(dto);
                    #endregion
                }
                var result = HttpClientHelper.PostResponseKey(konggaIP + "/transset/api/TransFer/CreateSheepTransFers", sheep);
                EditReproductivePresenceState.UpdateReproductivePresenceStatePL(earTag, 2, 2, konggaIP);
                #endregion
                return await db.SaveChangesAsync() > 0;
            }
            catch (Exception)
            {

                throw;
            }
           
        }


    }
}
